package com.geek.water.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import com.geek.water.dto.MenuDTO;
import com.geek.water.entity.Menu;
import com.geek.water.entity.Meta;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface MenuMapper extends BaseMapper<Menu> {

    //根据用户ID查询一级菜单
    @Select("SELECT DISTINCT m.* \n" +
            "FROM user u \n" +
            "JOIN user_role ur ON u.id = ur.user_id \n" +
            "JOIN role r ON ur.role_id = r.id \n" +
            "JOIN role_menu rm ON r.id = rm.role_id \n" +
            "JOIN menu m ON rm.menu_id = m.id \n" +
            "WHERE u.id = #{uid} AND m.level = 1 \n" +
            "ORDER BY m.priority")
    @Results({
            @Result(column = "meta_id" , property = "meta" , javaType = Meta.class ,
                    one = @One(select = "com.geek.water.mapper.MetaMapper.selectById"))
    })
    public List<Menu> selectFirstMenuByUid(Long uid);


    //根据父项ID，查询对应的二级菜单（不检查权限）
    @Select("SELECT m2.* \n" +
            "FROM menu m1 \n" +
            "JOIN menu m2 ON m1.id = m2.parentMenuId \n" +
            "WHERE m1.id = #{parentId} \n" +
            "ORDER BY m2.priority")
    @Results({
            @Result(column = "meta_id" , property = "meta" , javaType = Meta.class ,
                    one = @One(select = "com.geek.water.mapper.MetaMapper.selectById"))
    })
    public List<MenuDTO> selectSecondMenuByParentId(Integer parentId);

    //根据用户ID和父菜单ID，查询用户有权限的二级菜单
    @Select("SELECT DISTINCT m2.* \n" +
            "FROM user u \n" +
            "JOIN user_role ur ON u.id = ur.user_id \n" +
            "JOIN role r ON ur.role_id = r.id \n" +
            "JOIN role_menu rm ON CAST(r.id AS SIGNED) = rm.role_id \n" +
            "JOIN menu m1 ON rm.menu_id = m1.id \n" +
            "JOIN menu m2 ON m1.id = m2.parentMenuId \n" +
            "WHERE u.id = #{uid} AND m1.id = #{parentId} AND m2.level = 2 \n" +
            "ORDER BY m2.priority")
    @Results({
            @Result(column = "meta_id" , property = "meta" , javaType = Meta.class ,
                    one = @One(select = "com.geek.water.mapper.MetaMapper.selectById"))
    })
    public List<MenuDTO> selectSecondMenuByUidAndParentId(Long uid, Integer parentId);

}
